package com.vmc.util;

import java.io.File;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.vmc.exception.VMCException;
import com.vmc.strategy.Action;

public class DirectoryTraversalUtility {

	static Logger logger = LogManager.getLogger(DirectoryTraversalUtility.class);
	private static DirectoryTraversalUtility instance = new DirectoryTraversalUtility();
	
	private DirectoryTraversalUtility() {
		
	}
	
	public static DirectoryTraversalUtility getInstance() {
		return instance;
	}
	
	public void traverseDirectory(File directory, Action<File> action, Action<File> before, Action<File> after) throws VMCException {
		if (directory != null && directory.isDirectory() && directory.canRead()) {
			if (before != null) {
				before.performAction(directory);
			}
			traverseDirectory(directory, action);
			if (after!= null) {
				after.performAction(directory);
			}
		}
	}
	
	private boolean traverseDirectory(File directory, Action<File> action) throws VMCException {
		logger.info("Traversing " + directory.getName());
		boolean isAllPerformedSuccessfully = true;
		for (File file : directory.listFiles()) {
			if (file.isDirectory() && file.canRead()) {
				isAllPerformedSuccessfully = isAllPerformedSuccessfully && traverseDirectory(file, action);
			}
			else if (file.isFile() && file.canRead()) {
				isAllPerformedSuccessfully = isAllPerformedSuccessfully && action.performAction(file);
			}
		}
		logger.info("Done traversing " + directory.getName());
		return isAllPerformedSuccessfully;
	}
}
